package com.common.util.utils;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * @文件名称：IOUtils.java
 * @文件作者：ljb
 * @文件描述：
 * @版本： 1.0.0
 * @创建时间：2017-12-21 16:03
 * @修改历史：2017-12-21 16:03
 */

public class IOUtils {

    public static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        copyAllBytes(inputStream, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    public static byte[] readAllBytesAndClose(InputStream inputStream) throws IOException {
        byte[] bytes;
        try {
            bytes = readAllBytes(inputStream);
        } finally {
            safeClose(inputStream);
        }

        return bytes;
    }

    public static String readAllChars(Reader reader) throws IOException {
        char[] chars = new char[2048];
        StringBuilder sb = new StringBuilder();

        while(true) {
            int len = reader.read(chars);
            if(len == -1) {
                return sb.toString();
            }

            sb.append(chars, 0, len);
        }
    }

    public static String readAllCharsAndClose(Reader reader) throws IOException {
        String str = null;
        try {
            str = readAllChars(reader);
        } finally {
            safeClose(reader);
        }

        return str;
    }

    public static void writeAllCharsAndClose(Writer writer, CharSequence charSequence) throws IOException {
        try {
            writer.append(charSequence);
        } finally {
            safeClose(writer);
        }

    }

    public static int copyAllBytes(InputStream is, OutputStream os) throws IOException {
        int len = 0;
        byte[] bytes = new byte[4096];

        while(true) {
            int length = is.read(bytes);
            if(length == -1) {
                return len;
            }

            os.write(bytes, 0, length);
            len += length;
        }
    }

    public static void safeClose(Closeable closeable) {
        if(null != closeable) {
            try {
                if(closeable instanceof Flushable) {
                    ((Flushable)closeable).flush();
                }

                closeable.close();
            } catch (IOException ioe) {
            }

        }
    }
}
